<?php
namespace Operator\Model;

//营业收入报表
class ReportModel extends BaseModel
{

    //自营营业收入报表
    public function selfIncome($where)
    {
        // 查询满足要求的总记录数
        $count = M('line_orders')
            ->alias('o')
            ->field('count(*),sum(need_pay) as sum')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join("__PUBLIC_GROUP__ as p on o.group_id = p.group_id and p.group_status = 3")
            ->where($where)
            ->find();

        $Page = new \Think\Page($count['count(*)'], 15);
        $show = $Page->show();
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.order_num,o.total_num,o.end_need_pay,o.preferential,o.create_time,o.need_pay,l.line_name,r.receipt_num,p.group_num,sales_id,manager_id,origin_line_id')
            ->join('__PUBLIC_LINE__ l ON l.line_id=o.line_id and order_type = 1')
            ->join("__PUBLIC_GROUP__ as p on o.group_id = p.group_id and p.group_status = 3")
        // ->join('LEFT JOIN __OPERATOR_LINE_RESELLER__ u ON u.reseller_id =o.sales_id ')
            ->join('LEFT JOIN __PUBLIC_RECEIPT__ as r on r.order_id = o.order_id')
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
            // echo M()->_sql();die;
        $this->selfIncomeArrangeList($list);
        return ['list' => $list, 'all_total_money' => round($count['sum'], 2), 'show' => $show];
    }

    public function selfIncomeArrangeList(&$list)
    {
        $staff = M('operator_line_reseller')
            ->field('reseller_id, reseller_name, pid')
            ->where([
                'operator_id'      => session('operator_user.operator_id'),
                'reseller_flag'    => 1,
                'is_review'        => 1,
                'reseller_status'  => 1,
                'shop_or_reseller' => 1,
            ])
            ->select();
        $staff = $this->changeIndex($staff);
        foreach ($list as $k => $v) {
            $list[$k]['line_name'] .=  ($v['origin_line_id'] ? '' : '(自营)') ;
            $list[$k]['reseller_name'] = $staff[$v['sales_id']]['reseller_name'];
            $list[$k]['shop_name']     = $staff[$v['manager_id']]['reseller_name'];
            $list[$k]['payee']         = $staff[$v['manager_id']]['reseller_name'];
        }
    }

    //导出自营营业收入报表
    public function outSelfIncome($where)
    {
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.order_num,o.total_num,o.payee,o.end_need_pay,o.preferential,o.create_time,o.need_pay,l.line_name,r.receipt_num,p.group_num,sales_id,manager_id, origin_line_id')
            ->join('__PUBLIC_LINE__ l ON l.line_id=o.line_id and order_type = 1')
            ->join("__PUBLIC_GROUP__ as p on o.group_id = p.group_id and p.group_status = 3")
            ->join('LEFT JOIN __PUBLIC_RECEIPT__ as r on r.order_id = o.order_id')
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        $this->selfIncomeArrangeList($list);
        foreach ($list as $k => $v) {
            $list[$k]['order_info'] = implode("\n", ["订单号：{$v['order_num']}", "团号：{$v['group_num']}", "线路名称：{$v['line_name']}"]);
            $list[$k]['receipt_num'] .= ' ';
        }
        $title = [
            ['order_info', '订单信息'],
            ['shop_name', '门店'],
            ['reseller_name', '销售人员'],
            ['total_num', '人数'],
            ['need_pay', '订单总额'],
            ['end_need_pay', '实收金额'],
            ['preferential', '优惠金额'],
            ['payee', '收款人'],
            ['receipt_num', '发票号'],
        ];
        $file_name = '自营产品收入报表';
        D('ExportExcel')->exportExcels($file_name, $title, $list);
    }

    //营业收入报表
    public function businessStatement($where)
    {
        // 查询满足要求的总记录数
        $count =  M('line_orders')
            ->alias('o')
            ->field('g.group_id')
            ->join('LEFT JOIN __PUBLIC_GROUP__ as g on g.group_id = o.group_id ')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on o.line_id = l.line_id')
            ->group('g.group_id')
            ->where($where)
            ->select();
            $count = count($count);
        // 分页
        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        // 查询
        $list = M('line_orders')
            ->alias('o')
            //, r.adult_price, r.child_price, r.oldman_price
            ->field('g.group_id, g.group_num, l.line_name, platform, group_time, sum(total_num), sum(need_pay),closing_total_money')
            ->join('LEFT JOIN __PUBLIC_GROUP__ as g on g.group_id = o.group_id ')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on o.line_id = l.line_id')
            ->group('g.group_id')
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        // echo M()->_sql();die;
        $this->groupData($list);
        return ['list' => $list, 'show' => $show];
    }

    /**
     * 整理团数据
     * @param  [array] &$list [description]
     */
    public function groupData(&$list)
    {
        $group_id = implode(',', $this->levelDown($list));
        $addition = M('order_addition')
            ->field('group_id,sum(now_money) as sum')
            ->where(['group_id' => ['in', $group_id]])
            ->group('group_id')
            ->select();
        $addition = $this->changeIndex($addition);
        foreach ($list as $k => $v) {
            $type                      = $v['origin_line_id'] ? '非自营' : '自营';
            $list[$k]['info']          = implode("\n", ["团号：{$v['group_num']}", "线路名称：{$v['line_name']}({$type})"]);
            $list[$k]['group_time']    = date('Y-m-d', $v['group_time']);
            $list[$k]['add_income']    = isset($addition[$v['group_id']]) ? $addition[$v['group_id']]['sum'] : 0;
            $list[$k]['sum(need_pay)'] = round($list[$k]['sum(need_pay)'], 2);
            //自营线路 总收入—总成本+附加产品收入（自营）
            if ($v['origin_line_id']) {
                $list[$k]['profit'] = $v['sum(need_pay)'] - $v['closing_total_money'] + $list[$k]['add_income'];
                //供应商 总收入—总成本—附加产品收入（供应商）
            } else {
                $list[$k]['profit'] = $v['sum(need_pay)'] - $v['closing_total_money'] - $list[$k]['add_income'];
            }
            //毛利率
            $list[$k]['profit_precent'] = round($list[$k]['profit'] / $v['sum(need_pay)'] * 100, 2) . '%';
            $list[$k]['profit']         = round($list[$k]['profit'], 2);
            $list['sum_money'] += $list[$k]['sum(need_pay)'];
            $list['profit'] += $list[$k]['profit'];
        }
    }

    //导出营业收入报表
    public function outBusinessStatement()
    {
        $list = M('line_orders')
            ->alias('o')
            //, r.adult_price, r.child_price, r.oldman_price
            ->field('g.group_id, g.group_num, l.line_name, platform, group_time, sum(total_num), sum(need_pay),closing_total_money')
            ->join('LEFT JOIN __PUBLIC_GROUP__ as g on g.group_id = o.group_id ')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on o.line_id = l.line_id')
            ->group('group_id')
            ->where($where)
            ->order('o.order_id desc')
            // ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        $this->groupData($list);
        unset($list['sum_money']);
        unset($list['profit']);
        $title = [
            ['info', '订单信息'],
            ['group_time', '成团时间'],
            ['sum(total_num)', '该团总人数'],
            ['add_income', '附加产品收入'],
            ['sum(need_pay)', '营业额'],
            ['closing_total_money', '总成本'],
            ['profit', '毛利'],
            ['profit_precent', '毛利率'],
        ];
        $file_name = '营业收入报表';
        D('ExportExcel')->exportExcels($file_name, $title, $list);
    }

    //财务管理
    public function financialManagement($where)
    {
        // 查询满足要求的总记录数
        $count = M('line_orders')->alias('o')
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->where($where)
            ->getField('count(*)');
        // 分页
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show(); // 分页显示输出
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.*,l.line_name,l.source_type,l.group_num,l.line_sn')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->where($where)
            ->order('o.order_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->arrangeData($list);
        return ['list' => $list, 'show' => $show];
    }

    //导出财务管理
    public function outFinancialManagement($where)
    {
        // 查询
        $list = M('line_orders')->alias('o')
            ->field('o.*,l.line_name,l.source_type,l.group_num,l.line_sn')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->where($where)
            ->order('o.order_id desc')
            ->select();
        $this->arrangeData($list);
        $title = [
            ['shop', '分销/门店'],
            ['line_sn', '线路编号'],
            ['group_num', '团号'],
            ['order_num', '订单号'],
            ['total_num', '人数'],
            ['order_status', '订单状态'],
            ['end_need_pay', '收款金额'],
            ['pay_time', '收款日期'],
            ['payee', '收款员'],
            ['sales', '销售员'],
        ];
        $file_name = '财务管理';
        D('ExportExcel')->exportExcels($file_name, $title, $list);
    }

    /**
     * 整理数据
     * 将对应的销售人、负责人、城市的id换成中文
     * @param  [array] &$list
     */
    private function arrangeData(&$list)
    {
        $ms = D('Staff');
        // $reseller = $this->changeIndex($ms->getReseller());
        $shop = $this->changeIndex($ms->getSomeStaff([]));
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list[$k]['pay_time']    = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '未付款';
            $list[$k]['order_num'] .= ' ';
            $list[$k]['payee']        = $shop[$v['manager_id']]['reseller_name'];
            $list[$k]['order_status'] = $this->orderStatus($v['order_status']);
            $list[$k]['sales']        = $shop[$v['sales_id']]['reseller_name'];
            if ($v['order_type'] == 1) {
                $list[$k]['shop'] = $shop[$v['manager_id']]['reseller_name'] . '(自营)';
            } else {
                $list[$k]['shop'] = $shop[$v['manager_id']]['reseller_name'] . '(分销)';
            }
        }
    }

    /**
     * 订单状态选择
     * @param  [int] $status [订单状态]
     * @return [string]         [订单状态]
     */
    private function orderStatus($status)
    {
        switch ($status) {
            case -6:
                $status = '取消';
                break;
            case -5:
                $status = '已退款';
                break;
            case -4:
                $status = '拒绝退款';
                break;
            case -3:
                $status = '退款审核中';
                break;
            case -2:
                $status = '订单审核不通过';
                break;
            case -1:
                $status = '待支付';
                break;
            case 1:
                $status = '待审核(预订成功)';
                break;
            case 2:
                $status = '审核中';
                break;
            case 3:
                $status = '已审核';
                break;
        }
        return $status;
    }
}
